﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Windows.Forms;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace DM
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string pI = this.Request["pI"];
            string path = this.Request["path"];
            if (pI != null && path != null)
            {
                txPath.Text = path;
                btnSearchFiles_Click(pI, null);
            }
        }

        public string GetName(string name, char separator)
        {
            string[] parts = name.Split(separator);
            string retorno = "";
            for (int i = 0; i < parts.Length - 1; i++)
                retorno += parts[i] + separator.ToString();

            return retorno;
        }

        //clique do botao de busca arquivos
        protected void btnSearchFiles_Click(object sender, EventArgs e)
        {
            string pI = null;
            try
            {
                pI = (string)sender;
            }
            catch { pI = "0"; }
            

            try
            {


                string javasript = "";

                javasript += @"<Script>

$(function(){
	var playItem = " + pI + @",
		title=$('.jp-interface .jp-title'),
		jPlayer=$(""#jplayer""),
		myPlayList = [";


                if (txPath.Text != String.Empty)
                {

                    string pathFile = txPath.Text;

                    //string pathFile = "C:\\ADEMS_FILES\\" + "\\MoviesLegendFiles";
                    string html = @"<table class=""dates"" cellpadding=""0"" cellspacing=""0"" border=""0"">
                            <tr class=""thead"">
                              <td class=""col1"">Date / Venue</td>
                              <td class=""col2"">Location</td>
                              <td class=""col3"">Information</td>
                            </tr>";

                    DirectoryInfo pasta = new DirectoryInfo(pathFile);
                    FileInfo[] arquivos = pasta.GetFiles();

                    int count = 0;
                    int Max = 0;
                    foreach (FileInfo file in arquivos)
                    {
                        string[] parts = file.Name.Split('.');
                        if (parts[parts.Length - 1] == "mp3")
                        {
                            Max++;
                        }
                    }

                    foreach (FileInfo file in arquivos)
                    {
                        string[] parts = file.Name.Split('.');
                        if (parts[parts.Length - 1] == "mp3")
                        {
                            string name = "";
                            for (int i = 0; i < parts.Length - 1; i++)
                                name += parts[i];

                            string color = "";
                            if (count % 2 == 0)
                            {
                                color = @"class=""even""";
                            }
                            
                            string pathMusic = pathFile + "\\" + file.Name;

                            string pathMusicCopy = "C:\\projects\\LB\\DM\\DM\\audio\\";

                            //pathMusic = pathMusic.Replace('\\', '/');

                            if (!System.IO.File.Exists(pathMusicCopy + file.Name))
                            {
                                System.IO.File.Copy(pathMusic, pathMusicCopy + file.Name);
                            }

                            javasript += @"
			{name:""" + name + @""",mp3:""" + "audio/" +  file.Name + @""",ogg:""audio/black_plant.ogg""}";

                            if (count < Max - 1)
                                javasript += @", 
";
                            //pega as informacoes de detalhes do mp3
                            //Mp3 mp3 = LerMp3(file.OpenRead());

                            Mp3Lib.Mp3File mp3 = new Mp3Lib.Mp3File(pathMusic);

                            List<SearchResult> list = GoogleSearch(mp3.TagHandler.Artist, null);

                            html += @"<tr " + color + @">
                              <td class=""col1"">" + file.LastWriteTime.ToString() + @"<br>
                                <a href=""index.aspx?pI=" + count + @"&path=" + pathFile + @""" class=""name"">" + name + @"</a><br>
                                <a href=""#"" class=""facebook-event"">Compartilhar</a></td>
                              <td>" + file.Length.ToString() + @"<br>
                                " + file.Extension + @"</td>
                              <td>" + file.DirectoryName + @"</td>
                            </tr>";
                            count++;
                        }
                    }
                    html += "</table>";

                    dv_tb_files.InnerHtml = html;


                    javasript += @"
],		
		jPlay=function(idx){
			if(typeof idx==typeof 0)
				jPlayer.jPlayer(""setMedia"",myPlayList[idx]).jPlayer('play')
			if(typeof idx==typeof '')
				jPlayer.jPlayer(""setMedia"",myPlayList[playItem=idx=='next'?(++playItem<myPlayList.length?playItem:0):(--playItem>=0?playItem:myPlayList.length-1)]).jPlayer('play')					
			title.text(myPlayList[playItem].name)
			Cufon.refresh()
		}

	jPlayer.jPlayer({
		ready: function() {
			jPlay(playItem)
		},
		ended:function(){
			jPlay('next')
		}
	})
	
	$("".jp-prev,.jp-next"")
		.click( function() { 
			jPlay($(this).is('.jp-next')?'next':'prev')
			return false;
		})
	
});
</script>";

                    Page.ClientScript.RegisterStartupScript(this.GetType(), "script1", javasript);
                }
            }catch(Exception error)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "script2", @"<script>alert("""+error.Message+@""");</script>");
            }
        }


        public Mp3 LerMp3(System.IO.FileStream Arquivo)
        {
            string saida = "";
            Mp3 mp3 = new Mp3();

            byte[] buffer;
            // Le o stream do nosso arquivo
            using (System.IO.FileStream fs = Arquivo)
            {
                // Pega o tamanho do stream
                int size = Convert.ToInt32(fs.Length);
                // Move para ultima posição - 128
                fs.Position = size - 128;
                buffer = new byte[3];
                fs.Read(buffer, 0, 3);
                string s = System.Text.UTF8Encoding.UTF8.GetString(buffer, 0, 3).ToUpper().Trim();
                // Verifica se o aquivo tem tag definida
                if (s == "TAG")
                {
                    // Move para ultima posição - 125
                    fs.Position = size - 125;
                    buffer = new byte[100];
                    // Le 30 bytes a partir a posicao
                    fs.Read(buffer, 0, 30);
                    // TAG - MUSICA
                    mp3.Musica = System.Text.UTF8Encoding.UTF8.GetString(buffer, 0, 30);

                    // Move para ultima posição - 95
                    fs.Position = size - 95;
                    // Le 30 bytes a partir a posicao
                    fs.Read(buffer, 0, 30);
                    // TAG - ARTISTA
                    mp3.Artista = System.Text.UTF8Encoding.UTF8.GetString(buffer, 0, 30);

                    // Move para ultima posição - 69
                    fs.Position = size - 69;
                    // Le 30 bytes a partir a posicao
                    fs.Read(buffer, 0, 30);
                    // TAG - ALBUM
                    mp3.Album =  System.Text.UTF8Encoding.UTF8.GetString(buffer, 0, 30);

                    // Move para ultima posição - 39
                    fs.Position = size - 35;
                    // Le 30 bytes a partir a posicao
                    fs.Read(buffer, 0, 4);
                    // TAG - ANO
                    mp3.Ano = System.Text.UTF8Encoding.UTF8.GetString(buffer, 0, 4);
                }
                fs.Close();
            }
            return mp3;
        }

    public List<SearchResult> GoogleSearch(string search_expression, 
    Dictionary<string, object> stats_dict)
    {
        var url_template = GetSearchLink(search_expression);
      Uri search_url;
      var results_list = new List<SearchResult>();
      int[] offsets = { 0, 8, 16, 24, 32, 40, 48 };
      foreach (var offset in offsets)
      {
        search_url = new Uri(string.Format(url_template, search_expression, offset));
 
        var page = new WebClient().DownloadString(search_url);
 
        JObject o = (JObject)JsonConvert.DeserializeObject(page);
 
        var results_query =
          from result in o["responseData"]["results"].Children()
          select new SearchResult(
              url: result.Value<string>("url").ToString(),
              title: result.Value<string>("title").ToString(),
              content: result.Value<string>("content").ToString(),
              engine: SearchResult.FindingEngine.google
              );
 
        foreach (var result in results_query)
          results_list.Add(result);
      }
 
      return results_list;
    }

        public string GetSearchLink(string filter)
        {
            string ip = Request.ServerVariables["REMOTE_ADDR"];

            string url  = "";
            url         += "&v=1.0";
            url         += "&rsz=8";
            //url         += "&key=xxxxxxxxx";
            url         += "&userip=" + ip;
            url         += "&q=" + filter.Trim();
            url         += "&start=0";
 
            string link = "https://ajax.googleapis.com/ajax/services/search/images?" + url;
            return link;
        }
    }

  public class Mp3
    {
        public string Artista;
        public string Musica;
        public string Album;
        public string Ano;
        public string Genero;
        public int Byte;
    }


  public class SearchResult
  {
    public string url;
    public string title;
    public string content;
    public FindingEngine engine;
 
    public enum FindingEngine { google, bing, google_and_bing };
 
    public SearchResult(string url, string title, string content, FindingEngine engine)
    {
      this.url = url;
      this.title = title;
      this.content = content;
      this.engine = engine;
    }
  }

}